package com.ray.ba.starter.base.service;

import com.github.pagehelper.PageHelper;
import com.ray.ba.starter.base.mapper.Mapper;
import org.apache.ibatis.exceptions.TooManyResultsException;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Condition;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * BaseService
 *
 * @author ray
 * @date 2020/4/21
 */
public class BaseServiceImpl<T> implements BaseService<T> {

    @Autowired
    protected Mapper<T> mapper;

    private Class<T> entityClass;

    public BaseServiceImpl() {
        ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
        entityClass = (Class<T>) pt.getActualTypeArguments()[0];
    }

    @Override
    public T findById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public List<T> findByIds(Set<Long> ids) {
        String idsStr = ids.stream().map(Object::toString).collect(Collectors.joining(","));
        return mapper.selectByIds(idsStr);
    }

    @Override
    public List<T> findBy(Condition condition) {
        return mapper.selectByCondition(condition);
    }

    @Override
    public T findOne(T entity) {
        return mapper.selectOne(entity);
    }

    @Override
    public List<T> findBy(T entity) {
        return mapper.select(entity);
    }

    @Override
    public List<T> findBy(T entity, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return mapper.select(entity);
    }

    @Override
    public List<T> findAll() {
        return mapper.selectAll();
    }

    @Override
    public T insert(T entity) {
        mapper.insertSelective(entity);
        return entity;
    }

    @Override
    public void insert(List<T> entityList) {
        mapper.insertList(entityList);
    }

    @Override
    public T update(T entity) {
        mapper.updateByPrimaryKeySelective(entity);
        return entity;
    }

    @Override
    public void deleteById(Integer id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public void deleteByIds(Set<Long> ids) {
        String idsStr = ids.stream().map(Object::toString).collect(Collectors.joining(","));
        mapper.deleteByIds(idsStr);
    }
}
